﻿using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseSimpleAPI
{
    public class RouteData<T>
        where T : class
    {
        /// <summary>
        /// 格式化数据
        /// </summary>
        public List<string> Formats { get; set; }

        /// <summary>
        /// 名称与值之间的对应关系
        /// </summary>
        private ConcurrentDictionary<string, T> Name2ValueMapping = new ConcurrentDictionary<string, T>();

        /// <summary>
        /// 注册相关数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="t"></param>
        public bool Register(string key, T t)
        {
            return Name2ValueMapping.TryAdd(key, t);
        }

        /// <summary>
        /// 根据改变的值获取格式化Key
        /// </summary>
        /// <param name="change_data"></param>
        /// <returns></returns>
        public IEnumerable<string> GetFormatKeys(IDictionary<string, string> change_data)
        {
            List<string> keys = new List<string>();

            foreach (var format_item in Formats ?? new List<string>())
            {
                string key = format_item;
                foreach (var change_item in change_data)
                {
                    key = key.Replace("{" + change_item.Key + "}", change_item.Value);
                }

                if (key.IndexOf('{') == -1 && key.IndexOf('}') == -1)
                    keys.Add(key);
            }

            return keys;
        }

        /// <summary>
        /// 根据改变的数据查找对应数据
        /// </summary>
        /// <param name="change_data"></param>
        /// <returns></returns>
        public T FindValue(IDictionary<string, string> change_data)
        {
            return FindValue(GetFormatKeys(change_data));
        }

        /// <summary>
        /// 根据不确定个数的Key查找对象
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public T FindValue(params string[] keys)
        {
            return FindValue(new List<string>(keys));
        }

        /// <summary>
        /// 根据固定Key列表获取数据
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public T FindValue(IEnumerable<string> keys)
        {
            var def_t = default(T);

            foreach (var item in keys)
            {
                T t = FindValue(item);
                if (t != def_t)
                    return t;
            }

            return def_t;
        }

        /// <summary>
        /// 查找对应的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public T FindValue(string key)
        {
            if (Name2ValueMapping.TryGetValue(key, out T t))
                return t;

            return default(T);
        }
    }
}
